import requests


class AMap:
    def __init__(self, amap_key: str):
        self.AMAP_KEY = amap_key

    # 获取地图景点位置获取
    def amap_reverse_geocode(self, location: str, city: str = "北京") -> tuple:
        url = "https://restapi.amap.com/v3/geocode/geo"
        params = {
            "key": self.AMAP_KEY,
            "address": location,
            "city": city,
            "output": "json"
        }
        try:
            res = requests.get(url, params=params).json()
            if res["status"] == "1" and res["geocodes"]:
                loc = res["geocodes"][0]["location"]
                return tuple(loc.split(","))
        except Exception as e:
            print(f"高德逆地理编码失败: {e}")
        return None, None

    # 高德路径规划
    def get_amap_route(self, start_angular: str, end_angular: str) -> list:
        url = "https://restapi.amap.com/v3/direction/transit/integrated"
        params = {
            "key": self.AMAP_KEY,
            "origin": start_angular,
            "destination": end_angular,
            "city": "北京",
        }
        try:
            res = requests.get(url, params=params).json()
            print(res)
            if res["status"] == "1" and res["route"]["transits"]:
                routes = []
                for path in res["route"]["transits"]:
                    first_segment = path["segments"][0] if path["segments"] else {}
                    instruction = "无指引"
                    if "bus" in first_segment and first_segment["bus"].get("buslines"):
                        instruction = first_segment["bus"]["buslines"][0].get("name", "公交")
                    elif "walking" in first_segment and first_segment.get("walking"):
                        instruction = "步行"
                    routes.append({
                        "transport": instruction,
                        "route": instruction,
                        "duration": f"{int(path['duration']) // 60}分钟",
                        "distance": f"{int(path['distance']) / 1000:.1f}公里",
                        "cost": f"{path['cost']}元",
                        "walking_distance": f"{int(path['walking_distance'])}米",
                    })
                return routes
        except Exception as e:
            print(f"高德路径规划失败: {e}")
        return []